import {QuizModel} from '../../../database/models/quiz'

export const typeDefs = `
  type Quiz{
    _id: String
    question: String
    answer: String
    wrongAnswers:[String!]!
  } 
`

export const queryDefs = `
  getQuizs(page:Int): [Quiz]!
  searchQuiz(query:String): [Quiz]! 
`

export const mutationDefs = `
  addQuiz(
    question:String!,
    answer:String!,
    wrongAnswers:[String!]!
  ):Quiz!
  
   editQuiz(
    _id:String!,
    question:String!,
    answer:String!,
    wrongAnswers:[String!]!
  ):Quiz!
  
  deleteQuiz(_id:String!) : Boolean!
`

export const resolvers = {
  Query: {
    async getQuizs(_, {page = 0}) {
      const pageSize = 10

      const quizzes = await QuizModel.find()
        .sort({_id: -1})
        .limit(pageSize)
        .skip(page * pageSize)
        .lean()
      return quizzes
    },
    async searchQuiz(_, {query}) {
      const quizzes = await QuizModel.find({question: new RegExp(query)})
        .lean()
      return quizzes
    }
  },

  Mutation: {
    async addQuiz(_, {question, answer, wrongAnswers}) {
      const prize = new QuizModel({
        question, answer, wrongAnswers
      })
      await prize.save()
      return prize
    },

    async editQuiz(_, {_id, question, answer, wrongAnswers}) {
      const quiz = await QuizModel.findById(_id)

      if (quiz) {

        quiz.question = question
        quiz.answer = answer
        quiz.wrongAnswers = wrongAnswers

        await quiz.save()
        return quiz

      } else {
        throw Error('WRONG_QUIZ_ID')
      }
    },

    async deleteQuiz(_, {_id}) {
      await QuizModel.remove({_id})
      return true
    }
  }
}
